package com.baixun.gassystem.springsecurity;

import com.baixun.gascommon.exception.NoAuthorityFindException;
import com.baixun.gasentity.entity.SysAuthority;
import com.baixun.gasentity.entity.SysUser;
import com.baixun.gassystem.service.SysAuthorityService;
import com.baixun.gassystem.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户认证处理器
 */

@Service
public class MyUserServiceimpl implements UserDetailsService {
    @Autowired
    public SysUserService sysUserService;

    @Autowired
    public SysAuthorityService sysAuthorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getUserName,username);
        sysUserLambdaQueryWrapper.last("limit 1");
        SysUser one = sysUserService.getOne(sysUserLambdaQueryWrapper);
        if (one == null){
           throw  new UsernameNotFoundException("用户名未找到");
        }
        MyUserDetails myUserDetails = new MyUserDetails(one);
        //获取拥有的权限
        LambdaQueryWrapper<SysAuthority> sysAuthorityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysAuthorityLambdaQueryWrapper.eq(SysAuthority::getUserId,one.getId());
        List<SysAuthority> list = sysAuthorityService.list(sysAuthorityLambdaQueryWrapper);
        if (list == null){
            throw new NoAuthorityFindException("用户权限为空，账号信息错误！");
        }
        ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (SysAuthority sysAuthority : list) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(sysAuthority.getAuthority());
            simpleGrantedAuthorities.add(simpleGrantedAuthority);
        }
        myUserDetails.setSimpleGrantedAuthority(simpleGrantedAuthorities);
        return myUserDetails;
    }
}
